from app.libs.redprint import Redprint
from app.validators.forms import ClientForm
from app.libs.enums import ClientTypeEnum
from flask.globals import current_app
from flask.json import jsonify
from app.models.user import User
from itsdangerous.jws import TimedJSONWebSignatureSerializer

#注意要在app/api/v1/__init__.py中将红图注册到蓝图上
api = Redprint('token')

#默认路径为/v1/token
#post包含的数据比通过url传递的数据相对更安全
#?account=xxx@qq.com&password=123456
@api.route('', methods=['POST'])
def get_token():
    form = ClientForm().validate_for_api()
    promise = {ClientTypeEnum.USER_EMAIL: User.verify}
    #校验用户名和密码，校验成功后才能生成发送token
    identity = promise[ClientTypeEnum(form.reg_type.data)](form.account.data,
                                                           form.secret.data)
    
    #Token
    expiration = current_app.config['TOKEN_EXPIRATION']
    token = generate_auth_token(identity['uid'],
                                form.reg_type.data,
                                None,
                                expiration)
    #由于最终生成token序列是二进制的，所以这里要用decode('ascii')
    t = {'token': token.decode('ascii')}
    return jsonify(t), 201   #json格式返回消息，附带状态码

def generate_auth_token(uid, ac_type, scope=None, expiration=7200):
    #生成令牌(随机序列)
    s = TimedJSONWebSignatureSerializer(current_app.config['SECRET_KEY'], expires_in=expiration)
    
    #字典数据序列化
    return s.dumps({'uid': uid,
                    'type': ac_type.value})


